package com.villaday.idf.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import androidx.viewpager.widget.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.AppContext;
import com.villaday.idf.MainActivity;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.model.GuidesEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.StatusBarUtil;
import com.villaday.idf.util.StatusBarUtils;
import com.villaday.idf.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 启动页
 */
public class LogoActivity extends BaseActivity implements ViewPager.OnPageChangeListener, View.OnClickListener, OkHttpUtil.OnDataListener {

    @BindView(R.id.tv_skip)
    public TextView tvSkip;
    @BindView(R.id.img)
    ImageView img;

    @BindView(R.id.sdv)
    SimpleDraweeView sdv;


    private boolean isFirst;//是否首次启动
    private int countTime;
    private Handler handler;
    private List<ImageView> imgData;
    private Gson gson = new GsonBuilder().create();


    private Runnable runnable;
    private int position = -1;
    private GuidesEntity guidesEntity;
    private boolean isAd;

    private boolean isFirstResume = true;

    @Override
    protected int getViewResId() {
        return R.layout.activity_logo;
    }

    @Override
    protected void init() {
        //透明状态栏
        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            // Translucent status bar
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }*/

        StatusBarUtils.translucentStatusBar(this);
        StatusBarUtil.setLightMode(this);

        SharedPreferences isFirstShared = getSharedPreferences("isFirst", MODE_PRIVATE);

        isFirst = isFirstShared.getBoolean("IsFirstOpen", true);
        if (isFirst && false) {
            img.setVisibility(View.GONE);
            tvSkip.setVisibility(View.GONE);

        } else {


            startImg();

        }

        SharedPreferences.Editor editor = isFirstShared.edit();
        if (isFirst) {
            editor.putBoolean("IsFirstOpen", false);
        }
        editor.putBoolean("IsVerFirst", true);
        editor.commit();


    }

    @Override
    protected void loadData() {
        Map<String, String> map = new HashMap<>();

        map.put("code", "astgrsdagd");
        map.put("lang", "sdgadg");
        map.put("type", "2");

        OkHttpUtil.getJSON(this, Constant.URL.guides, this);
    }

    private void startImg() {
        img.setVisibility(View.VISIBLE);
        tvSkip.setVisibility(View.VISIBLE);

    }

        public void setData() {
        if (imgData == null) {
            imgData = new ArrayList<>();
        } else {
            imgData.clear();
        }


    }

    public void intoNextPage() {
//        SharedPreferencesUtil.saveToken(this, "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhdWQiOiJlYjA1ZWE2ZiIsInN1YiI6IllNTjlKZDAzeGsiLCJtdCI6MCwiYXBwSWQiOiJ5NmkzZkxTREhyejhBaEphIiwiZXhwIjoxNTY1ODM2MTEwLCJpYXQiOjE1MzQyOTk4MTAsInZlcnNpb24iOjEwMDAwMn0.LvcFnDGBtFABSgKKIcyCQIrok6TE7dlDJMypqy7gxPpSQFe4b2wr2Gto1OUj_fVsbDpkbdqD0PJKBDapJ9DYgw");
        if (!isAd) {
            if (TextUtils.isEmpty(SharedPreferencesUtil.getToken(this))) {
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
            } else {
                //初始化推送
                AppContext.getInstance().initPush();
                startActivity(MainActivity.class);
            }
            finish();
        }
    }


    @OnClick(R.id.tv_skip)
    public void skip() {
        handler = null;
        countTime = 0;
        intoNextPage();
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }


    @Override
    public void onPageSelected(int position) {
        if (position == 4) {
            handler = new Handler();
            countTime = 3;//初始秒数
            runnable = new Runnable() {
                @Override
                public void run() {
                    if (handler != null) {
                        tvSkip.setText(countTime + "s  跳过>>");
                        if (countTime <= 0) {
                            intoNextPage();
                        } else {
                            countTime--;
                            handler.postDelayed(this, 1000);
                        }
                    }
                }
            };
            handler.post(runnable);
        } else {

        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sdv: {
                if (position != -1) {
                    if (TextUtils.isEmpty(SharedPreferencesUtil.getToken(this))) {
                        return;
                    }
                    isAd = true;
                    if (guidesEntity.getBody().get(position).getJumpType() == 1) {//jumpType": "integer,跳转类型，1 APP页面跳转，
                        if (guidesEntity.getBody().get(position).getUrl().contains("page/house/detail?id=")) {//id为房源ID，如有其它参数原样带入查询
                            String[] split = guidesEntity.getBody().get(position).getUrl().split("=");

                            Intent intent1 = new Intent(this, HouseDetailsActivityFor3.class);
                            intent1.putExtra("houseId", split[1]);
                            intent1.putExtra("persellId", split[1]);
//                    intent.putExtra("type", data.get(position).getType());
                            startActivity(intent1);
                        } else if (guidesEntity.getBody().get(position).getUrl().contains("page/village/detail?id=")) {//id为目的地ID，如有其它参数原样带入查询
//"page/village/detail";  目的地详情页

                            String[] split = guidesEntity.getBody().get(position).getUrl().split("=");

                            Intent intent1 = new Intent(this, BourbonListActivity.class);

                            intent1.putExtra("villageId", split[1]);
                            intent1.putExtra("city", "");
                            intent1.putExtra("area", "");
                            startActivity(intent1);
                        } else if (guidesEntity.getBody().get(position).getUrl().contains("page/presell/detail?id=")) {//id为预售ID，如有其它参数原样带入查询
                            String[] split = guidesEntity.getBody().get(position).getUrl().split("=");

                            Intent intent1 = new Intent(this, HouseDetailsActivityFor3.class);
                            intent1.putExtra("houseId", split[1]);
                            intent1.putExtra("persellId", split[1]);
                            intent1.putExtra("presellProduct", true);
//              intent.putExtra("type", data.get(position).getType());
                            startActivity(intent1);
                        } else if (guidesEntity.getBody().get(position).getUrl().contains("page/village/list")) {//找房源-别墅
                            //初始化推送
                            AppContext.getInstance().initPush();
                            Intent intent = new Intent(this, MainActivity.class);


                            intent.putExtra("type", guidesEntity.getBody().get(position).getUrl());
                            startActivity(intent);

                        } else if (guidesEntity.getBody().get(position).getUrl().contains("page/house/list")) {//找房源-民宿
                            //初始化推送
                            AppContext.getInstance().initPush();
                            Intent intent = new Intent(this, MainActivity.class);


                            intent.putExtra("type", guidesEntity.getBody().get(position).getUrl());
                            startActivity(intent);
                        } else if (guidesEntity.getBody().get(position).getUrl().contains("page/member")) {//我的
                            //初始化推送
                            AppContext.getInstance().initPush();

                            Intent intent = new Intent(this, MainActivity.class);


                            intent.putExtra("type", guidesEntity.getBody().get(position).getUrl());
                            startActivity(intent);

                        } else if (guidesEntity.getBody().get(position).getUrl().contains("page/presell/search")) {//预售搜索
                            startActivity(new Intent(this, Home_temaiSearchActivity.class));

                        } else if (guidesEntity.getBody().get(position).getUrl().contains("page/home")) {//首页

                        }
                    } else if (guidesEntity.getBody().get(position).getJumpType() == 2) {//2 内嵌页面链接跳转，
                        Intent intent = new Intent(this, H5AutoTitleActivity.class);
                        intent.putExtra("title", "爱订房");
                        intent.putExtra("url", guidesEntity.getBody().get(position).getUrl());
                        startActivity(intent);
                    } else if (guidesEntity.getBody().get(position).getJumpType() == 3) {//3  跳转小程序",
                        wxOpenApplet(guidesEntity.getBody().get(position).getMiniAppId(), guidesEntity.getBody().get(position).getUrl(), guidesEntity.getBody().get(position).getMiniProgramType());
                    }
                }
            }
            break;
        }
    }


    private void startTime(int startTime) {
        handler = new Handler();
        countTime = startTime;//初始秒数
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (handler != null && tvSkip != null) {
                    tvSkip.setText(countTime + "s  跳过>>");
                    if (countTime <= 0) {
                        intoNextPage();
                    } else {
                        countTime--;
                        handler.postDelayed(this, 1000);
                    }
                }
            }
        });
    }

    /**
     * APP打开小程序
     */
    public void wxOpenApplet(String userName, String path, int miniProgramType) {
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID);
        if (!api.isWXAppInstalled()) {//未安装微信
            ToastUtil.initToast(this, "您未安装微信");
            return;

        }
        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = userName; // 填小程序原始id
        req.path = path;                  //拉起小程序页面的可带参路径，不填默认拉起小程序首页
        //      "miniProgramType": "integer,小程序版本，1：开发版 2：预览版 3：正式版，jumpType为3时必然存在"
        if (miniProgramType == 1) {
            req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_TEST;// 可选打开 开发版，体验版和正式版

        } else if (miniProgramType == 2) {
            req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;// 可选打开 开发版，体验版和正式版

        } else if (miniProgramType == 3) {
            req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版

        }

        api.sendReq(req);
    }

    @Override
    public void onResponse(String url, String json) {
        LogeUtil.e("guides", json);

        guidesEntity = gson.fromJson(json, GuidesEntity.class);
        if ("200".equals(guidesEntity.getCode())) {
            if (guidesEntity.getBody() != null && guidesEntity.getBody().size() > 0) {
                img.setVisibility(View.GONE);
                Random rand = new Random();
                position = rand.nextInt(guidesEntity.getBody().size());
                sdv.setImageURI(guidesEntity.getBody().get(position).getMaterial().getUrl());
                sdv.setOnClickListener(this);
                startTime(guidesEntity.getBody().get(position).getShowTime());
            }else {
                startTime(1);
            }

        }else {
            startTime(1);
        }
    }

    @Override
    public void onFailure(String url, String error) {
        LogeUtil.e("guides,error", error);
        startTime(1);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isFirstResume) {
            isAd = false;
            intoNextPage();
        }
        isFirstResume = false;

    }
}
